package cn.fboost.mtos.service.impl;

import cn.fboost.mtos.dto.Response;
import cn.fboost.mtos.service.UploadService;
import cn.fboost.mtos.util.ConfigUtil;
import cn.fboost.mtos.util.FileUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.StandardOpenOption;
import java.util.UUID;

@Slf4j
@Service
public class UploadServiceImpl implements UploadService {
    private final ConfigUtil configUtil;

    public UploadServiceImpl(ConfigUtil configUtil) {
        this.configUtil = configUtil;
    }

    @Override
    public Response upload(MultipartFile file) {
        String storagePath = configUtil.getString("upload.storage-path");
        String urlPrefix = configUtil.getString("upload.url-prefix");
        if (StringUtils.isBlank(storagePath) || StringUtils.isBlank(urlPrefix)) {
            return Response.builder().failure().msg("当前无法上传文件，请先配置存储策略").build();
        }

        String fileType = FileUtil.FILE_TYPE_MAP.getOrDefault(FileUtil.getFileHeader(file), null);
        if (fileType == null) {
            return Response.builder().failure().msg("不支持的文件类型").build();
        }

        String fileName = UUID.randomUUID() + "." + fileType;
        if (!storagePath.endsWith("/") && !storagePath.endsWith("\\")) {
            storagePath += File.separator;
        }

        Path path = new File(storagePath + fileName).toPath();
        try {
            Files.write(path, file.getBytes(), StandardOpenOption.CREATE_NEW, StandardOpenOption.WRITE);
            if (!urlPrefix.endsWith("/")) {
                urlPrefix += "/";
            }

            return Response.builder().success().msg("上传成功").data(urlPrefix + fileName).build();
        } catch (IOException e) {
            log.error("上传文件保存失败", e);
            return Response.builder().failure().msg("上传失败").build();
        }
    }
}
